import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';
import type User from './User.model';
import type Tenant from './Tenant.model';

/**
 * 文件模型
 */
class File extends Model {
  public id!: string;
  public tenantId?: string;
  public userId!: string;
  public originalName!: string;
  public fileName!: string;
  public mimeType!: string;
  public size!: number;
  public path!: string;
  public url?: string;
  public category!: 'document' | 'image' | 'video' | 'audio' | 'other';
  public bucket?: string;
  public storageType!: 'local' | 'oss' | 's3';
  public description?: string;
  public metadata?: any;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 关联属性
  public user?: User;
  public tenant?: Tenant;
}

File.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'tenant_id',
      comment: '租户ID',
    },
    userId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'user_id',
      comment: '上传用户ID',
    },
    originalName: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'original_name',
      comment: '原始文件名',
    },
    fileName: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'file_name',
      comment: '存储文件名',
    },
    mimeType: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'mime_type',
      comment: '文件类型',
    },
    size: {
      type: DataTypes.BIGINT,
      allowNull: false,
      comment: '文件大小（字节）',
    },
    path: {
      type: DataTypes.STRING(500),
      allowNull: false,
      comment: '文件存储路径',
    },
    url: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '文件访问URL',
    },
    category: {
      type: DataTypes.ENUM('document', 'image', 'video', 'audio', 'other'),
      allowNull: false,
      defaultValue: 'other',
      comment: '文件分类',
    },
    bucket: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: '存储桶名称（OSS/S3）',
    },
    storageType: {
      type: DataTypes.ENUM('local', 'oss', 's3'),
      allowNull: false,
      defaultValue: 'local',
      field: 'storage_type',
      comment: '存储类型',
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '文件描述',
    },
    metadata: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '文件元数据',
    },
  },
  {
    sequelize,
    tableName: 'files',
    underscored: true,
    timestamps: true,
    indexes: [
      {
        fields: ['tenant_id'],
      },
      {
        fields: ['user_id'],
      },
      {
        fields: ['category'],
      },
      {
        fields: ['storage_type'],
      },
      {
        fields: ['created_at'],
      },
    ],
  }
);

export default File;

